package com.sairobo.base.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.UUID;

/**
 *附件辅助类
 */
public class FileHelp {

    private final static Logger logger = LoggerFactory.getLogger(FileHelp.class);

    public static void saveMultiPartFile(MultipartFile myFile, String path, String filename) throws IOException {
        File targetFile = new File(path, filename);
        myFile.transferTo(targetFile);
    }

    /**
     * 文件下载
     *
     * @param fileUrl
     * @param realName
     * @param request
     * @param response
     */
    public static void downloadFile(String fileUrl, String realName, HttpServletRequest request, HttpServletResponse response) {

        try {
            String filePath = request.getSession().getServletContext().getRealPath(fileUrl);
            logger.info("下载的文件路径：" + filePath);
            FileHelp.setFileDownloadHeader(request, response, realName);
            File file = new File(filePath);
            FileInputStream inputStream = new FileInputStream(file);
            int len;
            byte[] buffer = new byte[100];
            while ((len = inputStream.read(buffer)) > 0)
                response.getOutputStream().write(buffer, 0, len);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 文件下载
     *
     * @param inputStream
     * @param realName
     * @param request
     * @param response
     */
    public static void downloadFile(InputStream inputStream, String realName, HttpServletRequest request, HttpServletResponse response) {
        try {
            FileHelp.setFileDownloadHeader(request, response, realName);
            int len;
            byte[] buffer = new byte[100];
            while ((len = inputStream.read(buffer)) > 0)
                response.getOutputStream().write(buffer, 0, len);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 文件下载
     *
     * @param path
     * @param realName
     * @param request
     * @param response
     */
    public static void downloadResourceFile(String path, String realName, HttpServletRequest request, HttpServletResponse response) {
        InputStream inputStream = getResource(path);
        try {
            FileHelp.setFileDownloadHeader(request, response, realName);
            int len;
            byte[] buffer = new byte[100];
            while ((len = inputStream.read(buffer)) > 0)
                response.getOutputStream().write(buffer, 0, len);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static InputStream getResource(String path) {
        return FileHelp.class.getResourceAsStream(path);
    }


    /**
     * 获取resource 路径文件的真实路径
     *
     * @param path
     * @return
     */
    public static String getResourceFilePath(String path) {
        URL url = FileHelp.class.getResource(path);
        return url.getPath();
    }

    /**
     * 获取Resource目录下的资源
     * @param resPath 路径
     * @return InputStream
     */
    public static InputStream getClassPathResource(String resPath) throws IOException {
        Resource resource = new ClassPathResource(resPath);
        return resource.getInputStream();
    }

    /**
     * 设置让浏览器弹出下载对话框的Header.
     *
     * @param request
     * @param response
     * @param fileName 下载后的文件名.
     */
    public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
        try {
            //中文文件名支持
            String agent = request.getHeader("WeChatUser-Agent");
            if (null != agent) {
                if (agent.contains("Firefox")) {
                    fileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
                } else if (agent.contains("Chrome")) {
                    fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
                } else {//IE7+
                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
                    fileName = StringUtils.replace(fileName, "+", "%20");//替换空格
                }
            }
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static void setExcelResponseHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
        try {
            //中文文件名支持
            String agent = request.getHeader("WeChatUser-Agent");
            if (null != agent) {
                if (agent.contains("Firefox")) {
                    fileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
                } else if (agent.contains("Chrome")) {
                    fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
                } else {//IE7+
                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
                    fileName = StringUtils.replace(fileName, "+", "%20");//替换空格
                }
            }
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setHeader("Content-Type", "application/octet-stream");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将文件扩展名转成小写
     *
     * @param fileName
     * @return
     */
    public static String setFileExtNameToLowerCase(String fileName) {
        String LowerCase = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        String headCode = fileName.substring(0, fileName.lastIndexOf("."));
        return headCode + LowerCase;
    }

    /**
     * 使用UUID替换本来的文件名
     *
     * @param fileName
     * @return
     */
    public static String createUUIDFileName(String fileName) {
        return UUID.randomUUID().toString().replace("-", "") + "." + StringUtils.substringAfter(fileName, ".");
    }
}
